<?php
/**
 * ccNewsletter
 * @author Chill Creations <info@chillcreations.com>
 * @link http://www.chillcreations.com
 * @license GNU/GPL
**/
// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');
jimport('joomla.application.component.controller');
class ccNewsletterControllersendNewsletter extends JController
{
	/**
	 * constructor (registers additional tasks to methods)
	 * @return void
	 */
	function __construct( $config = array() )
	{
		$this->_ccdata = array();
		parent::__construct( $config );
		//$this->registerTask( 'unpublish',	'publish' );
	}

	function display()
	{
		JRequest::setVar( 'view', 'sendNewsletter');
		JRequest::setVar( 'layout', 'form'  );
		parent::display();
	}

	function send_test()
	{
		global $mainframe;
   		// extract body for message and validate
		$body = JRequest::getVar( 'body','', 'post', 'string',JREQUEST_ALLOWRAW);
		//print_r($body);exit;
		jimport('joomla.mail.helper');
		$params = &JComponentHelper::getParams( 'com_ccnewsletter' );
        $fromName=$params->get('fromName');
        $fromEmail=$params->get('fromEmail');

		if (!$body)
		{
			$msg = JText::_( 'CC_MSG_BODY_EMPTY');
			$link = 'index.php?option=com_ccNewsletter&controller=sendNewsletter';
			$this->setRedirect($link, $msg);
			return false; // <-Exit Point. Task Failed.
		}

		// extract from name and validate
		//$fromName = JRequest::getVar( 'fromName','', 'post', 'string');
		if (!$fromName)
		{
			$msg = JText::_( 'CC_MSG_FROMNAME_EMPTY' );
			$link = 'index.php?option=com_ccNewsletter&controller=sendNewsletter';
			$this->setRedirect($link, $msg);
			return false; // <-Exit Point. Task Failed.
		}

		// extract from email and validate
		//$fromEmail = JRequest::getVar( 'fromEmail','', 'post', 'string');
		if (!$fromEmail)
		{
			$msg = JText::_( 'CC_MSG_FROMEMAIL_EMPTY' );
			$link = 'index.php?option=com_ccNewsletter&controller=sendNewsletter';
			$this->setRedirect($link, $msg);
			return false; // <-Exit Point. Task Failed.
		}

		// get the model, we need to get the test email address
		$nM =& $this->getModel('sendNewsletter');
		$params=$nM->getComponentParameters();
		$testEmailAddress = $params->get('testEmailAddress');

		// validate test email
		if (!$testEmailAddress)
		{
			$msg = JText::_( 'CC_MSG_TESTEMAIL_EMPTY' );
			$link = 'index.php?option=com_ccNewsletter&controller=sendNewsletter';
			$this->setRedirect($link, $msg);
			return false; // <- Exit Point. Task Failed.
		}

		// extract subject and validate
		$subject = JRequest::getVar( 'subject','', 'post', 'string');


		if (!$subject)
		{
			$msg = JText::_( 'CC_MSG_SUBJECT_EMPTY' );
			$link = 'index.php?option=com_ccNewsletter&controller=sendNewsletter';
			$this->setRedirect($link, $msg);
			return false; // <- Exit Point. Task Failed.
		}
		if($mainframe->getCfg('editor') == 'tinymce')
		{
			$body=$nM->convertInternalLink($body);
		}
		$body = str_replace("[".JText::_( 'CC_NAME' )."]", "[".JText::_( 'CC_TESTNAME_REPLACE' )."]", $body);
		$body = str_replace("[".JText::_( 'CC_UNSUBSCRIBE_LINK' )."]", "[".JText::_( 'CC_TESTEMAIL_REPLACE' )."]", $body);

		$body=$nM->convertImgTags($body);
		//$body=$nM->convertBackgroundTags($body);
		$body=$nM->convertInternalLink($body);


		jimport('joomla.mail.helper');
		// all fields validated, send mail.
		//$sendEmailStatus=JUtility::sendMail($fromEmail, $fromName, $testEmailAddress, $subject, $body,1);
		$mail = JFactory::getMailer();

		$mail->addRecipient( $testEmailAddress );
		$mail->setSender( array( $fromEmail, $fromName ) );
		$mail->addReplyTo( array( $fromEmail, $fromName ) );
		$mail->setSubject( $subject );

		// --- BEGIN : Embed images in the e-mail content ---
		// author : Emmanuel Guiton <egn@ccdig.fr>
		$doc = new DOMDocument();
		$body = htmlentities($body, ENT_NOQUOTES, 'UTF-8' ,false);
		$body = htmlspecialchars_decode($body);
		$doc->loadHTML($body);
		$imgs = $doc->getElementsByTagName('img');
		foreach ($imgs as $img)
		{
			$src = $img->getAttributeNode('src');
			$img_url  = $src->value;
			$site_url = JURI::base();
			$site_url = str_replace('/administrator', '', $site_url);
			$img_url  = str_replace($site_url, '', $img_url);
			$img_url  = '../'.$img_url;

			$dot_pos = strrpos($img_url, '.');
			$extension = substr($img_url, $dot_pos+1);
			$cid = basename($img_url, '.'.$extension);
			$src->value = 'cid:'.$cid;
			if ($extension == 'jpeg')
				$extension = 'jpg';
			$mail->AddEmbeddedImage( $img_url, $cid, $cid, "base64", "image/".$extension);
		}
		$body = $doc->saveHTML();
		// --- END : Embed images in the e-mail content ---

		$mail->setBody( $body );
		$mail->IsHTML(true);
		$sent = $mail->Send();

		// set user message and redirect back.
		$msg = JText::_( 'CC_MSG_TESTMAIL_SENT' ) .'&nbsp;'.  $testEmailAddress;
		$link = 'index.php?option=com_ccNewsletter&controller=sendNewsletter';
		$this->setRedirect($link, $msg);

		return true; // <-Exit Point. Task Successful.

	}
	function sendbatch()
	{
		$newsletterid = JRequest::getVar( 'newsletterToSend','', 'post', 'int');
		$start = JRequest::getVar( 'start','', 'post', 'int');

		if($start == 5)
		{
			echo "Process completed";
			exit;
		}
		else
		{
			$start++;

			echo "Process ID :" . $start;
			echo '<form action="index.php" method="post" name="adminForm" id="adminForm">';
			echo '<input type="hidden" name="start" value="'.$start.'" />';
			echo '<input type="hidden" name="newsletterToSend" value="'.$newsletterid.'" />';
			echo '</form>';
	    	echo '
	    	<script language="javascript">
				window.addEvent("domready"", sendmail()
				{

				}
	    	</script>';
			exit;
		}
	}

	function send_all()
	{
		global $mainframe;
		echo '<link href="components/com_ccnewsletter/assets/ccnewsleter.css" rel="stylesheet" type="text/css" />';
		flush();
		$nM =& $this->getModel('sendNewsletter');
		$params=$nM->getComponentParameters();
		$scripttimeout = $params->get('scripttimeout');
		$emailperbatch = $params->get('emailperbatch');
		$batchinterval = $params->get('batchinterval');
		$fromName = $params->get('fromName');
		$fromEmail = $params->get('fromEmail');
		$html_output = '';
		if (!ini_get('safe_mode'))
		{
			@set_time_limit(60 * $scripttimeout );
		}
		$temp=ini_get('max_execution_time');
		// echo 'max'.$temp;
		$minutes=$temp/60;

		//echo 'minutes'.$minutes;
		$time_start = microtime(true);
		$starttime=Date("Y-m-d H:i:s",$time_start);

		// Sleep for a while
		//echo 'Start Time'.$starttime;

		usleep(100);

		$date1 = strtotime(date("Y-m-d H:i:s", strtotime($starttime)) . " + $minutes minutes -2 seconds");
		//$date1 = strtotime(date("Y-m-d H:i:s", strtotime($starttime)) . " + $minutes minutes");
		$endtime=date("Y-m-d H:i:s",$date1);

		//echo 'End time:'.$endtime;


		ignore_user_abort();
		//set_time_limit(0);
		ini_set('display_errors', 0);


		$id = JRequest::getVar( 'id');
		//echo 'id='.$id;
		$db			=& JFactory::getDBO();
		$query ="SELECT `body`, `name` FROM #__ccnewsletter_newsletters WHERE id='".$id."'";
		$db->setQuery( $query );
		$row     = $db->loadObject();
		$body    = $row->body;
		$subject = $row->name;

		// extract body for message and validate
		//$body = JRequest::getVar( 'body','', 'post', 'string',JREQUEST_ALLOWRAW);

		jimport('joomla.mail.helper');
		$mail = JFactory::getMailer();

		if (!$body)
		{
			$msg = JText::_( 'CC_MSG_BODY_EMPTY' );
			$link = 'index.php?option=com_ccNewsletter&controller=sendNewsletter';
			$this->setRedirect($link, $msg);
			return false; // <-Exit Point. Task Failed.
		}

		// extract from name and validate
		//$fromName = JRequest::getVar( 'fromName','', 'post', 'string');
		if (!$fromName)
		{
			$msg = JText::_( 'CC_MSG_FROMNAME_EMPTY' );
			$link = 'index.php?option=com_ccNewsletter&controller=sendNewsletter';
			$this->setRedirect($link, $msg);
			return false; // <-Exit Point. Task Failed.
		}

		// extract from email and validate
		//$fromEmail = JRequest::getVar( 'fromEmail','', 'post', 'string');
		if (!$fromEmail)
		{
			$msg = JText::_( 'CC_MSG_FROMEMAIL_EMPTY');
			$link = 'index.php?option=com_ccNewsletter&controller=sendNewsletter';
			$this->setRedirect($link, $msg);
			return false; // <-Exit Point. Task Failed.
		}

		// get the model, we need to get the test email address

		$testEmailAddress = $params->get('testEmailAddress');

		// validate test email
		if (!$testEmailAddress)
		{
			$msg = JText::_( "The test email address is empty! Send Message routine aborted.");
			$link = 'index.php?option=com_ccNewsletter&controller=sendNewsletter';
			$this->setRedirect($link, $msg);
			return false; // <- Exit Point. Task Failed.
		}


		// extract subject and validate
		//$subject = JRequest::getVar( 'subject','', 'post', 'string');
		if (!$subject)
		{
			$msg = JText::_( 'CC_MSG_TESTEMAIL_EMPTY' );
			$link = 'index.php?option=com_ccNewsletter&controller=sendNewsletter';
			$this->setRedirect($link, $msg);
			return false; // <- Exit Point. Task Failed.
		}




		//all fields have been validated, send the test email as a copy
		$testSubject=JText::_( 'CC_COPY_OF' ) .' ' . $subject;
		$testbody = str_replace("[".JText::_( 'CC_NAME' )."]", "[".JText::_( 'CC_TESTNAME_REPLACE' )."]", $body);
		$testbody = str_replace("[".JText::_( 'CC_UNSUBSCRIBE_LINK' )."]", "[".JText::_( 'CC_TESTEMAIL_REPLACE' )."]", $testbody);

		$testbody=$nM->convertImgTags($testbody);
		$testbody=$nM->convertBackgroundTags($testbody);
		$testbody=$nM->convertInternalLink($testbody);




		//$sendEmailStatus=JUtility::sendMail($fromEmail, $fromName, $testEmailAddress, $testSubject, $testbody,1);
		$mail->addRecipient( $testEmailAddress);
		$mail->setSender( array( $fromEmail, $fromName ) );
		$mail->addReplyTo( array( $fromEmail, $fromName ) );
		$mail->setSubject( $testSubject );

		// --- BEGIN : Embed images in the e-mail content ---
		// author : Emmanuel Guiton <egn@ccdig.fr>
		$doc = new DOMDocument();
		$testbody = htmlentities($testbody, ENT_NOQUOTES, 'UTF-8' ,false);
		$testbody = htmlspecialchars_decode($testbody);
		$doc->loadHTML($testbody);
		$imgs = $doc->getElementsByTagName('img');
		foreach ($imgs as $img)
		{
			$src = $img->getAttributeNode('src');
			$img_url  = $src->value;
			$site_url = JURI::base();
			$site_url = str_replace('/administrator', '', $site_url);
			$img_url  = str_replace($site_url, '', $img_url);
			$img_url  = '../'.$img_url;

			$dot_pos = strrpos($img_url, '.');
			$extension = substr($img_url, $dot_pos+1);
			$cid = basename($img_url, '.'.$extension);
			$src->value = 'cid:'.$cid;
			if ($extension == 'jpeg')
				$extension = 'jpg';
			$mail->AddEmbeddedImage( $img_url, $cid, $cid, "base64", "image/".$extension);
		}
		$testbody = $doc->saveHTML();
		// --- END : Embed images in the e-mail content ---

		$mail->setBody( $testbody );
		$mail->IsHTML(true);
		$sent = $mail->Send();

		while (ob_get_level() > 0)
		{
			ob_end_flush();
		}

		$temp = JRequest::getVar('compsend');
		//echo 'test'.$temp;exit;
		$query = "SELECT id  FROM #__ccnewsletter_subscribers WHERE id='".$temp."'";
		$db->setQuery( $query );
		$id = $db->loadResult();
		//echo 'id='.$id;
		$db			=& JFactory::getDBO();
		$query = ' SELECT *  FROM #__ccnewsletter_subscribers WHERE enabled=1 ORDER BY id ASC';

		if( $temp != '')
		{
			//$query = ' AND id >'.$id;
			$query = 'SELECT *  FROM #__ccnewsletter_subscribers WHERE enabled=1 AND id > '.$id.' ORDER BY id ASC ';
		}

		$db->setQuery( $query );
		$subscribers = $db->loadObjectList();
		//print_r($subscribers);exit;
		// total up number of records to send
		$n = count( $subscribers );

		$newsletterModel =$this->getModel('sendNewsletter');

		$end_time = microtime(true);
		$endtime1=Date("Y-m-d H:i:s",$end_time);

		$query="SELECT count(*)  FROM #__ccnewsletter_subscribers WHERE enabled=1";
		$db->setQuery( $query );
		$total_sub = $db->loadResult();
		//echo 'Total:'.$total_sub;
		//$b=1;
		$mails = array();
		$main_html = '<center><div class="main-wrapper1">';
		$main_html .= '<div class="leftheader"></div>';
		$main_html .= '<div class="middleheader">';
		$main_html .= '<div class="headertitle">';
		$main_html .= JText::_( 'CC_NEWSLETTER_TITLE'). '&nbsp;' . JText::_( 'CC_SENDING_BATCH_EMAIL').'&nbsp;-&nbsp;'.JText::_( 'CC_SEND_NEWS').'&nbsp;'.$subject.'&nbsp;'.JText::_( 'CC_SEND_TO').'&nbsp;'.$total_sub.'&nbsp;'.JText::_( 'CC_SEND_SUB1');
		$main_html .= '</div>';
		$main_html .= '</div>';
		$main_html .= '<div class="rightheader"></div>';
		$main_html .= '<div class="clear"></div>';
		$main_html .= '<div class="content-wrapper"><div class="content">';
		$main_html .= '<div class="status_conf">';
		$main_html .= '<table width="100%"><tr>';
		//$main_html .= '<td align="left">'.JText::_( 'CC_BATCH').'&nbsp;'.$b.':'.'&nbsp;'.JText::_( 'CC_COMPLETED').' : <span id="sendemail" class="process"> 0 </span> of '. $n . '</td>';
		$batch = JRequest::getVar('batch');
		/*$sendcomp = JRequest::getVar('sendcomp');
		$sendcvalue = JRequest::getVar('sendcvalue');*/


		if($temp != '')
		{
			$b=$batch;
			//$sendcomp1=$sendcomp;
			/*$c=0;
			for($h=2;$h<=$b;$h++)
			{

					$m=$total_sub-($sendcomp*$c);
					$main_html .= '<tr><td align="left">'.JText::_( 'CC_BATCH').'&nbsp;'.($h-1).':'.'&nbsp;'.JText::_( 'CC_COMPLETED').' : <span  class="process"> '.($sendcomp+1).' </span> of '. $m . '</td></tr>';
					$c++;

			}*/

				$config_filename  = JPATH_SITE.DS.'administrator'.DS.'components'.DS.'com_ccnewsletter'.DS.'views'.DS. 'sendnewsletter'.DS. 'data.txt';
				$handle=@fopen($config_filename,'r');

				//if($handle)
				//{
					//while(!feof($handle))
					//{
						//$lines[]=fgets($handle,4096);
						//$lines=fread($handle, 4096);
						$length=filesize ($config_filename);
						$lines=fread($handle,$length-2 );
						$pieces = explode("\n", $lines);
						foreach($pieces as $piece)
						{
						$small_pieces[] = explode("-", $piece);
						}
						unset($piece);
						foreach( $small_pieces as $small_piece)
						{

							//echo 'Successfully Send='.$small_piece[0];
							//echo 'Batch='.$small_piece[1];
							//echo 'Total='.$small_piece[2];
							$main_html .= '<tr><td align="left">'.JText::_( 'CC_BATCH').'&nbsp;'.$small_piece[0].':'.'&nbsp;'.JText::_( 'CC_COMPLETED').' : <span id="sendemail3" class="process"> '. $small_piece[1].' </span> of '. $small_piece[2] . '</td></tr>';

						}
						unset($small_piece);
					//}
					fclose($handle);
				//}

					$main_html .= '<tr><td align="left">'.JText::_( 'CC_BATCH').'&nbsp;'.$b.':'.'&nbsp;'.JText::_( 'CC_COMPLETED').' : <span id="sendemail" class="process"> 0 </span> of '. $n . '</td></tr>';
		}
		else
		{
			$b=1;
			$main_html .= '<tr><td align="left">'.JText::_( 'CC_BATCH').'&nbsp;<span id="batch"> '.$b.' </span>:'.'&nbsp;'.JText::_( 'CC_COMPLETED').' : <span id="sendemail" class="process"> 0 </span> of '. $n . '</td></tr>';
		}
		$main_html .= '<td align="right"><span id="waiting" ></span></td>';
		$main_html .= '</tr></table>';
		$main_html .= '<table width="100%"><tr>';
		$main_html .= '<td align="center" id="message" style="color:red;font-weight:bold;">'.JText::_( 'CC_DONT_CLOSE');
		$main_html.='</td></tr></table>';
		//$main_html .='<td id="redirect_home">'.JText::_( '');
		//$main_html.='</td></a>';

		$main_html .= '<table width="100%"><tr><td align="left"><div id="comp"></div></td><td align="right"><div id="comp_yno"></div></td></tr></table>';
		$main_html .='</div><ul  style="list-style:none;"">';
		$main_html .='<table width="100%"><tr><td align="right"><a id="redirect_home" href="index.php?option=com_ccnewsletter&controller=sendNewsletter">'.JText::_( '').'</a></td></tr></table>';

		echo $main_html;
		flush();


		for ($i = 0; $i < $n; $i++)
		{
			//ob_start();

			$mails[$i] = JFactory::getMailer();

			$convertedBody=$newsletterModel->convertUnsubscribeLink($body,$subscribers[$i]->id);

			$convertedBody=$newsletterModel->convertSubscribeName($convertedBody,$subscribers[$i]->name);

			$convertedBody=$newsletterModel->convertImgTags($convertedBody);
			$convertedBody=$newsletterModel->convertBackgroundTags($convertedBody);
			$convertedBody=$newsletterModel->convertInternalLink($convertedBody);

			$mails[$i]->addRecipient( $subscribers[$i]->email );
			$mails[$i]->setSender( array( $fromEmail, $fromName ) );
			$mails[$i]->addReplyTo( array( $fromEmail, $fromName ) );
			$mails[$i]->setSubject( $subject );

			// --- BEGIN : Embed images in the e-mail content ---
			// author : Emmanuel Guiton <egn@ccdig.fr>
			$doc = new DOMDocument();
			$convertedBody = htmlentities($convertedBody, ENT_NOQUOTES, 'UTF-8' ,false);
			$convertedBody = htmlspecialchars_decode($convertedBody);
			$doc->loadHTML($convertedBody);
			$imgs = $doc->getElementsByTagName('img');
			foreach ($imgs as $img)
			{
				$src = $img->getAttributeNode('src');
				$img_url  = $src->value;
				$site_url = JURI::base();
				$site_url = str_replace('/administrator', '', $site_url);
				$img_url  = str_replace($site_url, '', $img_url);
				$img_url  = '../'.$img_url;

				$dot_pos = strrpos($img_url, '.');
				$extension = substr($img_url, $dot_pos+1);
				$cid = basename($img_url, '.'.$extension);
				$src->value = 'cid:'.$cid;
				if ($extension == 'jpeg')
					$extension = 'jpg';
				$mails[$i]->AddEmbeddedImage( $img_url, $cid, $cid, "base64", "image/".$extension);
			}
			$convertedBody = $doc->saveHTML();
			// --- END : Embed images in the e-mail content ---

			$mails[$i]->setBody( $convertedBody );
			$mails[$i]->IsHTML(true);
			$sent = $mails[$i]->Send();

			$j = $i + 1;


			$html_output .= '<li><div class="emaillist"><div style="float:left;width:50px;">' . ($i+1) . '. </div>';
			$html_output .= '<div style="float:left;width:400px;text-align:left;">'. $subscribers[$i]->email . '</div>';
			$html_output .= '<div style="float:left;width:48px;">';
			for($k = 0; $k < 40000; $k++)
			{
				echo ' '; // extra spaces
			}
			if ($mails[$i]->error_count > 0)
			{
				$html_output .=  '<img src="components/com_ccnewsletter/assets/publish_x.png" width="16" height="16" />';
			}
			else
			{
				$html_output .=  '<img src="components/com_ccnewsletter/assets/tick.png" width="16" height="16" />';
			}

			$html_output .= '</div></div></li>';

			echo $html_output;
			$html_output = '';
			flush();
			usleep(50000);

			echo '<script type="text/javascript" language="javascript">document.getElementById(\'sendemail\').innerHTML = \' '.($i + 1) .' \'</script>';
			//flush();

			$query = "SELECT id  FROM #__ccnewsletter_newsletters WHERE name='".$subject."'";
			$db->setQuery( $query );
			$id = $db->loadResult();

			$end_time = microtime(true);
			$endtime1=Date("Y-m-d H:i:s",$end_time);
			$date2 = strtotime(date("Y-m-d H:i:s", strtotime($endtime1)) . "-1 seconds");
			$endtime2=date("Y-m-d H:i:s",$date2);
			//echo 'end:'.$endtime2;

			if($endtime==$endtime1)
			{
				//echo 'Time expired';
				$b++;
				echo '<script type="text/javascript" language="javascript">document.getElementById(\'message\').innerHTML = \' '.JText::_( 'CC_ERROR').' \'; </script>';
				echo '<script type="text/javascript" language="javascript">document.getElementById(\'comp\').innerHTML = \' '.JText::_( 'CC_BATCH').'&nbsp;'.$b.':'.'&nbsp;'.JText::_( 'CC_COMPLETED').': <span id="sendemail1" class="process"> 0 </span> of <span id="sendemail2">' .$n. ' </span>  \'; </script>';
				echo '<script type="text/javascript" language="javascript">document.getElementById(\'sendemail1\').innerHTML = \' '.(0).' \'</script>';
				echo '<script type="text/javascript" language="javascript">document.getElementById(\'sendemail2\').innerHTML = \' '.($n-($i + 1)).' \'</script>';
				$testmail=$subscribers[$i]->email;
				$id1=$subscribers[$i]->id;
				$config_filename  = JPATH_SITE.DS.'administrator'.DS.'components'.DS.'com_ccnewsletter'.DS.'views'.DS. 'sendnewsletter'.DS. 'data.txt';
				//echo ''.$config_filename;
				$fp = fopen($config_filename, 'a+');
				fwrite($fp, $b-1);
				fwrite($fp, "-");
				fwrite($fp, $i+1);
				fwrite($fp, "-");
				fwrite($fp, $n);
				//fwrite($fp, ":");
				fwrite($fp, "\r\n");
				//echo''."\n";
				fclose($fp);
				echo '<script type="text/javascript" language="javascript">document.getElementById(\'comp_yno\').innerHTML = \' '.JText::_( 'CC_CONTINUE').' <a href="index.php?option=com_ccnewsletter&controller=sendNewsletter&task=send_all&compsend='.$id1.'&id='.$id.'&batch='.$b.'">'.JText::_( 'CC_SEND_YES').'</a> &nbsp;&nbsp;<a href="index.php?option=com_ccnewsletter&controller=sendNewsletter">'.JText::_( 'CC_SEND_CANCEL').' </a> \'; </script>';
				//echo '<script type="text/javascript" language="javascript">document.getElementById(\'message\').innerHTML = \' '.JText::_( 'CC_SUCCESS').' \'; </script>';
				exit;
			}

			if(($i+1) % $emailperbatch == 0)
				{

					for($count_seconds = ($batchinterval) ;$count_seconds > 0; $count_seconds--)
					{
						$end_time = microtime(true);
						$endtime1=Date("Y-m-d H:i:s",$end_time);
						$date2 = strtotime(date("Y-m-d H:i:s", strtotime($endtime1)) . "-1 seconds");
						$endtime2=date("Y-m-d H:i:s",$date2);
						//echo 'end:'.$endtime2;
						if($endtime==$endtime1)
						{
							$b++;
							echo '<script type="text/javascript" language="javascript">document.getElementById(\'message\').innerHTML = \' '.JText::_( 'CC_ERROR').' \'; </script>';
							echo '<script type="text/javascript" language="javascript">document.getElementById(\'comp\').innerHTML = \' '.JText::_( 'CC_BATCH').'&nbsp;'.$b.':'.'&nbsp;'.JText::_( 'CC_COMPLETED').': <span id="sendemail1" class="process"> 0 </span> of <span id="sendemail2">' .$n. ' </span>  \'; </script>';
							echo '<script type="text/javascript" language="javascript">document.getElementById(\'sendemail1\').innerHTML = \' '.(0).' \'</script>';
							echo '<script type="text/javascript" language="javascript">document.getElementById(\'sendemail2\').innerHTML = \' '.($n-($i + 1)).' \'</script>';
							$testmail=$subscribers[$i]->email;
							$id1=$subscribers[$i]->id;
							//echo 'id='.$id;
							$config_filename  = JPATH_SITE.DS.'administrator'.DS.'components'.DS.'com_ccnewsletter'.DS.'views'.DS. 'sendnewsletter'.DS. 'data.txt';
							//echo ''.$config_filename;
							$fp = fopen($config_filename, 'a+');
							fwrite($fp, $b-1);
							fwrite($fp, "-");
							fwrite($fp, $i+1);
							fwrite($fp, "-");
							fwrite($fp, $n);
							//fwrite($fp, ":");
							fwrite($fp, "\r\n");
							//echo''."\n";
							fclose($fp);
							echo '<script type="text/javascript" language="javascript">document.getElementById(\'comp_yno\').innerHTML = \' '.JText::_( 'CC_CONTINUE').' <a href="index.php?option=com_ccnewsletter&controller=sendNewsletter&task=send_all&compsend='.$id1.'&id='.$id.'&batch='.$b.'">'.JText::_( 'CC_SEND_YES').'</a>&nbsp;&nbsp; <a href="index.php?option=com_ccnewsletter&controller=sendNewsletter">'.JText::_( 'CC_SEND_CANCEL').' </a> \'; </script>';
							//echo '<script type="text/javascript" language="javascript">document.getElementById(\'message\').innerHTML = \' '.JText::_( 'CC_SUCCESS').' \'; </script>';
							exit;

						}
						sleep(1);
						echo '<script type="text/javascript" language="javascript">document.getElementById(\'waiting\').innerHTML = \''.JText::_( 'CC_WAITING').' '.$count_seconds .' '.JText::_( 'CC_SECONDS').'\'</script>';
						flush();

					}

					echo '<script type="text/javascript" language="javascript">document.getElementById(\'batch\').innerHTML = \' '.($b+1).' \'; </script>';
					$b++;
				}


			echo '<script type="text/javascript" language="javascript">document.getElementById(\'waiting\').innerHTML = \'\'; </script>';
			flush();

		}
		echo '</ul></div></div></div></center>';
		flush();
		//$link = 'index.php?option=com_ccnewsletter&controller=sendNewsletter';
		//echo '<script type="text/javascript" language="javascript">location.href=\''.$link .'\';</script>';
		echo '<script type="text/javascript" language="javascript">document.getElementById(\'message\').innerHTML = \' '.JText::_( 'CC_SUCCESS').' \'; </script>';
		echo '<script type="text/javascript" language="javascript">document.getElementById(\'redirect_home\').innerHTML = \' '.JText::_( 'CC_CLICK_HERE').' \'; </script>';
		exit;
	}

	function send_batch_msg( $ccsend = false )
	{
		echo '<link href="components/com_ccnewsletter/assets/ccnewsleter.css" rel="stylesheet" type="text/css" />';
		flush();

		$subject = JRequest::getVar( 'subject','', 'post', 'string');
		$id = JRequest::getVar( 'newsletterToSend','', 'post', 'string');

		$fromName = JRequest::getVar( 'fromName','', 'post', 'string');
		$fromEmail = JRequest::getVar( 'fromEmail','', 'post', 'string');

		$db =& JFactory::getDBO();
		$query = "SELECT *  FROM #__ccnewsletter_subscribers WHERE `enabled`=1 AND (`lastSentNewsletter` != $id OR `lastSentNewsletter` IS NULL)";
		$db->setQuery( $query );
		$subscribers = $db->loadObjectList();

		/*$query = "SELECT id  FROM #__ccnewsletter_newsletters WHERE name='".$subject."'";
		$db->setQuery( $query );
		$id = $db->loadResult();*/

		// total up number of records to send
		$n = count( $subscribers );

		while (ob_get_level() > 0)
		{
    		ob_end_flush();
    	}

		$config_filename  = JPATH_SITE.DS.'administrator'.DS.'components'.DS.'com_ccnewsletter'.DS.'views'.DS. 'sendnewsletter'.DS. 'data.txt';
		//echo ''.$config_filename;
		if(JPath::setPermissions(JPATH_SITE.DS.'administrator'.DS.'components'.DS.'com_ccnewsletter'.DS.'views'.DS. 'sendnewsletter'.DS. 'data.txt', '0644', '0755'))
    	{
		$fp = fopen($config_filename, 'w');
		fclose($fp);
    	}
		$conf_html = '<form action="index.php"><center><div class="main-wrapper">';
		$conf_html .= '<div class="leftheader"></div>';
		$conf_html .= '<div class="middleheader">';
		$conf_html .= '<div class="headertitle">';
		$conf_html .= JText::_( 'CC_NEWSLETTER_TITLE'). '&nbsp;' . JText::_( 'CC_SENDING_BATCH_CONF');
		$conf_html .= '</div>';
		$conf_html .= '</div>';
		$conf_html .= '<div class="rightheader"></div>';
		$conf_html .= '<div class="clear"></div>';
		$conf_html .= '<div class="content-wrapper"><div class="content">';
		$conf_html .= '<div class="status_conf">';
		$conf_html .= JText::_( 'CC_CONFORMATION');
		$conf_html .= '</br>';
		$conf_html .=JText::_( 'CC_CONFORMATION_FIRST');
		$conf_html .= '</div>';
		$conf_html .= '<div class="status">';
		$conf_html .=JText::_( 'CC_SEND_NEWS').'&nbsp;'.$subject.'&nbsp;'.JText::_( 'CC_SEND_TO').'&nbsp;'.$n.'&nbsp;'.JText::_( 'CC_SEND_SUB');
		$conf_html .= '</br>';
		$conf_html .= '<div class="confirmation">';
		if ( $ccsend )
			$conf_html.='<a href="index.php?option=com_ccnewsletter&controller=sendNewsletter&task=ccsend_all_first&id='.$id.'">';
		else
			$conf_html.='<a href="index.php?option=com_ccnewsletter&task=send_all&id='.$id.'">';
		$conf_html .=JText::_( 'CC_SEND_YES');
		$conf_html.='</a>'.'&nbsp;'.'&nbsp;'.'&nbsp;'.'&nbsp;';
		$conf_html.='<a href="index.php?option=com_ccnewsletter&controller=sendNewsletter&id='.$id.'">';
		$conf_html .=JText::_( 'CC_SEND_CANCEL');
		$conf_html.='</a>';
		$conf_html .= '</div>';
		$conf_html .= '</div>';
		$conf_html .= '</div></div>';

		echo $conf_html;
		flush();
		exit;
	}

	/**
	 * @brief Alternative function to confirm sending the newsletter
	 *
	 * @author Emmanuel Guiton <egn@ccdig.fr>
	 * @version 1.0.5
	 * @since 1.0.5
	 * @date September 2009
	 */
	function ccsend()
	{
		$this->send_batch_msg(true);
	}

	/**
	 * @brief Initiate first call to ccsend_all()
	 *
	 * @author Emmanuel Guiton <egn@ccdig.fr>
	 * @version 1.0.5
	 * @since 1.0.5
	 * @date September 2009
	 */
	function ccsend_all_first()
	{
		$this->ccsend_all( false );
	}

	/**
	 * @brief Alternative controller function to send the newsletter to all the subscribers
	 *
	 * Direct call to this function are considered made from an ajax script.
	 *
	 * @author Emmanuel Guiton <egn@ccdig.fr>
	 * @version 1.0.5
	 * @since 1.0.5
	 * @date September 2009
	 *
	 * @param[in] $ajax tell if this is the first call to this function or if it is a subsequent call made from the ajax script
	 */
	function ccsend_all( $ajax = true )
	{
		global $mainframe;

		if ( $ajax )
		{
			ob_clean(); // Clean the output buffer
			header('Content-Type: text/xml'); // Set sent content as XML
			echo '<?xml version="1.0"?>';
		}

		$newsletterModel =& $this->getModel( 'sendNewsletter' );
		$newsletterModel->ccsend_all( $ajax );

		if ( !$ajax )
		{
			// Display sending interface
			$view = & $this->getView( 'sendnewsletter', 'html' );
			// Push the model into the view
			$view->setModel($newsletterModel, true);
			// Set the layout
			$view->setLayout( 'ccsend' );
			$view->display();

			return true; // <-Exit Point. Task Successful.
		}
		else
		{
			$ccdata = $newsletterModel->get_ccdata();
			foreach( $ccdata['results'] as $result )
			{
				?><tr>
					<td style="text-align: center;"><?php echo $result['index']; ?></td>
					<td><?php echo $result['email']; ?></td>
					<td style="text-align: center;"><?php echo $result['sent']; ?></td>
				</tr><?php
			}
			if ( isset($ccdata['message']) )
			{
				?><input id="stop" value="stop" type="hidden" /><?php
			}
			// Discards any further HTML output
			ob_flush(); // Sends the output buffer
			exit; // Stops the script
		}
	}
}
?>


